package edu.sdjzu.config;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Date;

@Component
public class JwtUtils {

    @Value("${jwt.secret}")
    private String secret;

    @Value("${jwt.expiration}")
    private long expiration;

    private SecretKey secretKey;

    @PostConstruct
    public void init() {
        System.out.println("JwtUtils 初始化，secret: " + secret);
        // 使用新版的 Keys.hmacShaKeyFor 方法
        secretKey = Keys.hmacShaKeyFor(secret.getBytes(StandardCharsets.UTF_8));
    }

    public String generateToken(Long userId, String username) {
        System.out.println("生成 token，userId: " + userId + ", username: " + username);
        return Jwts.builder()
                .setSubject(userId.toString())
                .claim("userId", userId)
                .claim("username", username)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + expiration * 1000))
                .signWith(secretKey)  // 新版 API 不需要指定算法
                .compact();
    }

    public Claims parseToken(String token) throws JwtException {
        System.out.println("開始解析 token: " + token);
        try {
            Claims claims = Jwts.parserBuilder()
                .setSigningKey(secretKey)
                .build()
                .parseClaimsJws(token)
                .getBody();
            System.out.println("Token 解析成功，claims: " + claims);
            return claims;
        } catch (Exception e) {
            System.out.println("Token 解析失敗: " + e.getMessage());
            throw e;
        }
    }
}
